package com.biubiux2.security;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author noexcs
 * @since 8/9/2022 1:54 PM
 */
public class DESUtil {

    public static Cipher getEncryptCipher(SecretKey secretKey) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(secretKey.getEncoded());
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        SecretKey convertSecretKey = factory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
        return cipher;
    }

    public static Cipher getDecryptCipher(SecretKey secretKey) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(secretKey.getEncoded());
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        SecretKey convertSecretKey = factory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
        return cipher;
    }

    public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        generator.init(new SecureRandom());
        return generator.generateKey();
    }

    public static String convertKeyToString(SecretKey key) {
        return Base64.encodeBase64String(key.getEncoded());
    }

    public static SecretKey convertStringToKey(String keyStr) throws Exception {
        byte[] bytes = Base64.decodeBase64(keyStr);

        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
        return secretKeyFactory.generateSecret(new DESKeySpec(bytes));
    }
}
